//
//  RecommendViewController.m
//  WuLi
//
//  Created by Gollum on 16/8/30.
//  Copyright © 2016年 Gollum. All rights reserved.
//
#pragma mark - modelRec
#import "RecAttached.h"
#import "RecData.h"
#import "RecNewscoverinfo.h"
#import "RecNewsimageinfolist.h"
#import "RecommendModel.h"
#import "RecParamap.h"
#import "RecWebpimageinfolist.h"

#pragma mark - modelPk
#import "RecPKAttached.h"
#import "RecPKData.h"
#import "RecPKModel.h"
#import "RecPKParamap.h"
#import "RecPKVotedetailinfo.h"
#import "RecPKVoteoptioninfolist.h"
#import "RecPKVotestatisticinfo.h"

#import "RecommendViewController.h"
#import "BigImageCellTableViewCell.h"
#import "PettyTableViewCell.h"
#import "VideoTableViewCell.h"
#import "RecPKTableViewCell.h"
#import "RecTopicTableViewCell.h"
//调用互动的cell
#import "ProphesyTableViewCell.h"
#import "TestTableViewCell.h"
//工具
#import "NetworkTool.h"
#import "UIImageView+WebCache.h"
//#import "VideoPlayer.h"
//#import "Color+Hex.h"
//#import "UIViewExt.h"
#import "WMPlayer.h"

//子VC
#import "BIgImageViewController.h"
#import "PettyImageViewController.h"
#import "RVideoViewController.h"
#import "TopicViewController.h" //互动中的话题
#import "PKViewController.h"
#import "SearchViewController.h"
//使用互动中的详情VC
#import "TestDetailViewController.h"
#import "ProphesyDetailViewController.h"


#import "JHNewGuideView.h"
//夜间模式

#define KBigImageCellTableViewCellReuse @"BigImage"
#define kPettyTableViewCellReuse @"PettyImage"
#define kVideoTableViewCellReuse @"VideoReuse"
#define kRecPKTableViewCellReuse @"RecPkReuse"
#define kRecTopicTableViewCellReuse @"RecTopic"

#import "MJRefresh.h"
@interface RecommendViewController ()<UITableViewDataSource,UITableViewDelegate>
//model
//因数据结构不同建立两种model- PK与其他数据结构在parmap上很大不同
@property (nonatomic,strong)RecommendModel *recommend;
@property (nonatomic,strong)RecPKModel *recPk;

@property (nonatomic,strong)NSMutableArray <RecData *>*dataSourceArray;

@property (nonatomic,strong)NSMutableArray <RecPKData*>*PkDataArray;



@property (nonatomic,assign)NSInteger i;
@property (nonatomic,assign)NSInteger num;
@property (nonatomic,strong)NSMutableArray *array;


//headerView
@property (nonatomic,weak)IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UIButton *shearchButton;

//@property (assign, nonatomic)BOOL isSmallScreen;
//@property (nonatomic,strong)VideoTableViewCell *currentCell;//当前播放的cell
@property (strong, nonatomic)NSIndexPath *currentIndexPath;
@property (nonatomic,strong)RVideoViewController *rVideo;


//新手引导
@property (strong, nonatomic) JHNewGuideView *guideView;

@end

@implementation RecommendViewController
//- (NSMutableArray *)dataSourceArray {
//    if (!_dataSourceArray) {
//        _dataSourceArray = [NSMutableArray array];
//    }
//    return _dataSourceArray;

//}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];



}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _num = 0;
    _i = 2;
//   self.dataSourceArray = [NSMutableArray array];
//   self.PkDataArray = [NSMutableArray array];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 112) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsVerticalScrollIndicator = NO;
    

    //创建头视图
    [self createTableViewHeaderView];
    
    //注册cell
    [_tableView registerNib:[UINib nibWithNibName:@"BigImageCellTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:KBigImageCellTableViewCellReuse];
    
    [_tableView registerNib:[UINib nibWithNibName:@"PettyTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kPettyTableViewCellReuse];
    
    [_tableView registerNib:[UINib nibWithNibName:@"VideoTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kVideoTableViewCellReuse];
    //pk
    [_tableView registerNib:[UINib nibWithNibName:@"RecPKTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kRecPKTableViewCellReuse];
    
    [_tableView registerNib:[UINib nibWithNibName:@"RecTopicTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kRecTopicTableViewCellReuse];
    
    [_tableView registerNib:[UINib nibWithNibName:@"ProphesyTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"Prophesy"];
    
    [_tableView registerNib:[UINib nibWithNibName:@"TestTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"Test"];
    
    
    
    //刷新
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self handleData];

            [_tableView.mj_header endRefreshing];

        });
    }];
    
    
    [self.tableView.mj_header beginRefreshing];

    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self handleData2];
            

            [_tableView.mj_footer endRefreshing];
        });
    }];
    
    
    
}












- (void)handleData{
    
    
    
    self.recommend = [[RecommendModel alloc] init];
    //获取当前时间
    NSDate *senddate = [NSDate date];
    //时间转为字符串
    NSString *date = [NSString stringWithFormat:@"%ld", (long)[senddate timeIntervalSince1970]];
    
    
    NSString *str1 = @"http://211.151.51.100/v2/message/list?timestamp=";
    NSString *str2 = [NSString stringWithFormat:@"123&pageIndex=1"];
    NSString *str3 = @"&pageSize=10";
    NSString *urlString = [[[str1 stringByAppendingString:date] stringByAppendingString:str2] stringByAppendingString:str3];
    
    //    NSString *urlString = @"http://211.151.51.80/v2/message/list?timestamp=0&pageIndex=1&pageSize=10";
    NSDictionary *header = @{@"User-Agent":@"Dalvik/2.1.0 (Linux; U; Android 5.0; ASUS_Z00ADB Build/LRX21V) Wuli/2.3.1 (agent:s;channel:wandoujia;credential:e1MyMDEwMDAxMDF9LXsjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIzM1Nzg3MjA2MTcxNDM4M30teyMjIyMjIyMxNDcyMDAyMTMyOTYzLTJlZjRjNThjZDJ9QDE0NzExODgxOTgzODY=;deviceId:357872061714383;osTypeId:01;detailInfo:android;simTypeId:01;netTypeId:01;deviceTypeId:01;osVersion:5.0;idfa:null)", @"Host":@"api.5wuli.com"};
    [NetworkTool GET:urlString andBody:nil andHeader:header andResponse:JHJSON andSuccessBlock:^(id result) {
//        NSLog(@"_________________________%@",result);
        self.recommend = [RecommendModel modelWithDic:result];
        self.recPk = [RecPKModel modelWithDic:result];
        _dataSourceArray = _recommend.data.mutableCopy;
        _PkDataArray = _recPk.data.mutableCopy;
//        [self.PkDataArray addObject:_recPk];
        //加数据
        //        [self.array addObject:_recommend.data];
        
        [self.tableView reloadData];
        
    } andFailureBlock:^(NSError *error) {
        
    }];
    
}

- (void)handleData2{
    
    
//    self.recommend = [[RecommendModel alloc] init];
    //获取当前时间
    NSDate *senddate = [NSDate date];
    //时间转为字符串
    NSString *date = [NSString stringWithFormat:@"%ld", (long)[senddate timeIntervalSince1970]];
    
    
    NSString *str1 = @"http://211.151.51.100/v2/message/list?timestamp=";
    NSString *str2 = [NSString stringWithFormat:@"345&pageIndex=%ld",_i];
    NSLog(@"=======%ld",_i);
    NSString *str3 = @"&pageSize=10";
    NSString *urlString = [[[str1 stringByAppendingString:date] stringByAppendingString:str2] stringByAppendingString:str3];
    
    //    NSString *urlString = @"http://211.151.51.80/v2/message/list?timestamp=0&pageIndex=1&pageSize=10";
    NSDictionary *header = @{@"User-Agent":@"Dalvik/2.1.0 (Linux; U; Android 5.0; ASUS_Z00ADB Build/LRX21V) Wuli/2.3.1 (agent:s;channel:wandoujia;credential:e1MyMDEwMDAxMDF9LXsjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIzM1Nzg3MjA2MTcxNDM4M30teyMjIyMjIyMxNDcyMDAyMTMyOTYzLTJlZjRjNThjZDJ9QDE0NzExODgxOTgzODY=;deviceId:357872061714383;osTypeId:01;detailInfo:android;simTypeId:01;netTypeId:01;deviceTypeId:01;osVersion:5.0;idfa:null)", @"Host":@"api.5wuli.com"};
    [NetworkTool GET:urlString andBody:nil andHeader:header andResponse:JHJSON andSuccessBlock:^(id result) {
        
        self.recommend = [RecommendModel modelWithDic:result];
        self.recPk = [RecPKModel modelWithDic:result];
        
        for (int i = 0; i < _recommend.data.count; i ++) {
            [_dataSourceArray addObject:_recommend.data[i]];
        }
        
        for (int i = 0; i < _recPk.data.count; i ++) {
            [_PkDataArray addObject:_recPk.data[i]];
        }
        [self.tableView reloadData];
        
    } andFailureBlock:^(NSError *error) {
        
    }];
    
    _i ++;
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    


}











//- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    if ([scrollView isKindOfClass:[UITableView class]]) {
//        if (scrollView.contentOffset.y == 0) {
//            NSLog(@"1111111111111111111111111");
//            _tableView.contentOffset = CGPointMake(0, 44);
//        }
//    }
//    }
//
//- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
//
// 
//
//}




- (void)createTableViewHeaderView{
    
    
    
    //创建头视图iuhiuhu
    [[NSBundle mainBundle] loadNibNamed:@"RecHeaderView" owner:self options:nil];
    self.headerView.frame = CGRectMake(0, 0, self.view.frame.size.width, 44);
    
    _tableView.tableHeaderView = _headerView;
    _shearchButton.clipsToBounds = YES;
    _shearchButton.layer.cornerRadius = 14;
//    [_tableView setContentInset:UIEdgeInsetsMake(-44, 0, 0, 0)];

}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    NSLog(@"我的layoutType-------------------%@",_recPk.data[indexPath.row].title);
//    NSLog(@"我的layoutType-------------------%@",_recPk.data[indexPath.row].layoutType);
    if ([_dataSourceArray[indexPath.row].layoutType isEqualToString:@"VIDEO"]||[_dataSourceArray[indexPath.row].layoutType isEqualToString:@"BIG"]) {
        return 340;
    }
    else if ([_PkDataArray[indexPath.row].layoutType isEqualToString:@"TOPIC"]||[_dataSourceArray[indexPath.row].layoutType isEqualToString:@"GUESS"]||[_dataSourceArray[indexPath.row].layoutType isEqualToString:@"QUIZ"]){
        
        return  200;
    
    }else if ([_dataSourceArray[indexPath.row].layoutType isEqualToString:@"VOTE_BIG_TEXT"]){
        return 100;
    
    }

    else
//        if ([_recommend.data[indexPath.row].layoutType isEqualToString:@"SINGLE"])
    {
        return 115;
    }
//    else
    
//    return 0;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
//    for (int i = 0; i < _dataSourceArray.count; i++) {
//        NSDictionary *dic = [_dataSourceArray objectAtIndex:i];
//      NSArray *dataArray = [dic objectForKey:@"data"];
//    }
    
    NSLog(@"%ld",_dataSourceArray.count);
    return _dataSourceArray.count;
}





- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if ([_dataSourceArray[indexPath.row].layoutType isEqualToString:@"BIG"]) {
        BigImageCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:KBigImageCellTableViewCellReuse];
//        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_recommend.data[indexPath.row].newsImageInfoList[0].url]];
//        cell.mainImage.image = [UIImage imageWithData:data];
        NSURL *url = [NSURL URLWithString:_dataSourceArray[indexPath.row].newsImageInfoList[0].url];
        [cell.mainImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"default_image"]];
        cell.title.text = _dataSourceArray[indexPath.row].title;
        cell.origin.text = _dataSourceArray[indexPath.row].origin;
        cell.commentTotalCount.text = [NSString stringWithFormat:@"%ld",_dataSourceArray[indexPath.row].commentTotalCount];
        return cell;
    }
    else if([_dataSourceArray[indexPath.row].layoutType isEqualToString:@"VIDEO"]) {
        VideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kVideoTableViewCellReuse];
        
        NSURL *url = [NSURL URLWithString:_dataSourceArray[indexPath.row].newsImageInfoList[0].url];
        [cell.mainView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"default_image"]];
        
        cell.title.text = _dataSourceArray[indexPath.row].title;
        cell.origin.text = _dataSourceArray[indexPath.row].origin;
        cell.commentTotalCount.text = [NSString stringWithFormat:@"%ld",_dataSourceArray[indexPath.row].commentTotalCount];
        
        NSString *logo = @"#";
        cell.labelName.text  = [[logo stringByAppendingString:_dataSourceArray[indexPath.row].paraMap.labelName] stringByAppendingString:logo];

        return cell;
    }
    else if ([_PkDataArray[indexPath.row].layoutType isEqualToString:@"VOTE_BIG_TEXT"]){
    
        RecPKTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kRecPKTableViewCellReuse];
        cell.title.text = _PkDataArray[indexPath.row].title;
        cell.commentTotalCount.text = [NSString stringWithFormat:@"%ld",_PkDataArray[indexPath.row].commentTotalCount];
        return cell;
    
    }else if ([_dataSourceArray[indexPath.row].layoutType isEqualToString:@"TOPIC"]){
        RecTopicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kRecTopicTableViewCellReuse];
        cell.title.text = _PkDataArray[indexPath.row].title;
        NSURL *url = [NSURL URLWithString:_dataSourceArray[indexPath.row].newsImageInfoList[0].url];
        [cell.mainImage sd_setImageWithURL:url];
        return cell;
    }
    else if ([_dataSourceArray[indexPath.row].layoutType isEqualToString:@"GUESS"]){
        ProphesyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Prophesy"];
        NSURL *url = [NSURL URLWithString:_dataSourceArray[indexPath.row].newsImageInfoList[0].url];
        [cell.mainImage sd_setImageWithURL:url];
        cell.title.text = _dataSourceArray[indexPath.row].title;
        return cell;
    }
    else if([_dataSourceArray[indexPath.row].layoutType isEqualToString:@"QUIZ"]){
        TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Test"];
        NSURL *url = [NSURL URLWithString:_dataSourceArray[indexPath.row].newsImageInfoList[0].url];
        [cell.mainImage sd_setImageWithURL:url];
        cell.title.text = _dataSourceArray[indexPath.row].title;
        return cell;
    }
    else{
        
        PettyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kPettyTableViewCellReuse];
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_dataSourceArray[indexPath.row].newsImageInfoList[0].url]];
        cell.mainImage.image = [UIImage imageWithData:data];
        cell.title.text = _dataSourceArray[indexPath.row].title;
        
        cell.origin.text = _dataSourceArray[indexPath.row].origin;
        
        cell.commentTotalCount.text = [NSString stringWithFormat:@"%ld",_dataSourceArray[indexPath.row].commentTotalCount];
        
        return cell;
    }
    
    }


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if ([_dataSourceArray[indexPath.row].layoutType isEqualToString:@"BIG"]) {
        
        BIgImageViewController *bigImage = [[BIgImageViewController alloc] init];
        
        bigImage.detailString = _dataSourceArray[indexPath.row].detailLink;
        bigImage.parentId = _dataSourceArray[indexPath.row].parentId;
        bigImage.parentType = _dataSourceArray[indexPath.row].parentType;
        bigImage.newsId = _dataSourceArray[indexPath.row].newsId;
        bigImage.newsType = _dataSourceArray[indexPath.row].newsType;
        bigImage.newsEngineType = _dataSourceArray[indexPath.row].newsSourceType;
        bigImage.layoutType = _dataSourceArray[indexPath.row].layoutType;
        
        
        [self presentViewController:bigImage animated:YES completion:^{
            
        }];
    }
    else if([_dataSourceArray[indexPath.row].layoutType isEqualToString:@"SINGLE"]){
        PettyImageViewController *pettyImage = [[PettyImageViewController alloc] init];
        pettyImage.detailString = _dataSourceArray[indexPath.row].detailLink;
        pettyImage.parentId = _dataSourceArray[indexPath.row].parentId;
        pettyImage.parentType = _dataSourceArray[indexPath.row].parentType;
        pettyImage.newsId = _dataSourceArray[indexPath.row].newsId;
        pettyImage.newsType = _dataSourceArray[indexPath.row].newsType;
        pettyImage.newsEngineType = _dataSourceArray[indexPath.row].newsSourceType;
        pettyImage.layoutType = _dataSourceArray[indexPath.row].layoutType;

        [self presentViewController:pettyImage animated:YES completion:^{
            
        }];
    }else if([_dataSourceArray[indexPath.row].layoutType isEqualToString:@"VIDEO"]){
        RVideoViewController *rVideo = [[RVideoViewController alloc] init];
        rVideo.videoUrl = _dataSourceArray[indexPath.row].srcLink;
        rVideo.detailString = _dataSourceArray[indexPath.row].detailLink;
        [self presentViewController:rVideo animated:YES completion:^{
            
        }];
        

        
        [UIView animateWithDuration:0.5 animations:^{
            _rVideo.view.alpha = 1;
        }];
        
        
    }
    else if ([_PkDataArray[indexPath.row].layoutType isEqualToString:@"VOTE_BIG_TEXT"]){
        PKViewController *pk = [[PKViewController alloc] init];
        pk.detailString = _PkDataArray[indexPath.row].paraMap.voteDetailInfo.shareLink;
        [self presentViewController:pk animated:YES completion:^{
            
        }];
    
    }else if ([_dataSourceArray[indexPath.row].layoutType isEqualToString:@"QUIZ"]){
    //测试
        TestDetailViewController *test = [[TestDetailViewController alloc] init];
        test.detailString = _dataSourceArray[indexPath.row].newsImageInfoList[0].url;
        [self presentViewController:test animated:YES completion:^{
            
        }];
    }
    else if ([_dataSourceArray[indexPath.row].layoutType isEqualToString:@"GUESS"]){
    //押宝
        ProphesyDetailViewController *prophesy = [[ProphesyDetailViewController alloc] init];
        prophesy.detailLinkString = _dataSourceArray[indexPath.row].shareUrl;
        [self presentViewController:prophesy animated:YES completion:^{
            
        }];
    
    
    }
    else if([_dataSourceArray[indexPath.row].layoutType isEqualToString:@"TOPIC"]){
        //话题
        TopicViewController *topic = [[TopicViewController alloc] init];
        topic.detailString = _dataSourceArray[indexPath.row].shareUrlV2;
        
        [self presentViewController:topic animated:YES completion:^{
            
        }];
        
    }
    else{
            
    }
}




- (IBAction)shearchButton:(id)sender {
    SearchViewController *search = [[SearchViewController alloc] init];
    [self presentViewController:search animated:YES completion:^{
        
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
